package services

import (
	"Bok/daos"
	"Bok/models"
	"errors"
	"time"
)

type ArticalService interface {
	CreateArtical(v models.CreateArticleRequest, authorID uint) (*models.Article, error)
	GetArticalById(id uint) (v *models.Article, err error)
	ListArticles(page, pageSize int, status string) ([]models.Article, int64, error)
	UpdateArticle(id uint, req models.CreateArticleRequest) (*models.Article, error)
	DeleteArticle(id uint) error
}

type articalService struct {
	articalDao daos.ArticalDao
}

func NewArticleService(
	articalDao daos.ArticalDao,
) ArticalService {
	return &articalService{
		articalDao: articalDao,
	}
}

// 创建文章
func (s *articalService) CreateArtical(req models.CreateArticleRequest, authorID uint) (*models.Article, error) {
	// 处理业务

	// 生成 slug（短标签）
	// 用于标识和定位一个特定的页面或资源，通常用于URL中，使其更加友好和可读

	// 检查分类是否存在

	// 检查标签是否存在

	// 设置发布时间

	var createTime *time.Time
	var nowTime = time.Now()
	createTime = &nowTime

	article := &models.Article{
		Title:       req.Title,
		Content:     req.Content,
		CoverImage:  req.CoverImage,
		State:       req.State,
		TOC:         req.TOC,
		PublishedAt: createTime,
	}
	// 组织数据，进行创建
	// 调用 dao 层接口
	if err := s.articalDao.Create(article); err != nil {
		return nil, err
	}
	return article, nil
}

// 获取单个文章
func (s *articalService) GetArticalById(id uint) (v *models.Article, err error) {
	return s.articalDao.GetById(id)
}

// 分页获取文章列表
func (s *articalService) ListArticles(page, pageSize int, state string) ([]models.Article, int64, error) {
	// 处理一些业务逻辑（比如判断 是否合法）
	if page < 1 {
		page = 1
	}
	if pageSize < 1 || pageSize > 100 {
		pageSize = 10
	}
	return s.articalDao.List(page, pageSize, state)
}

// 更新文章
func (s *articalService) UpdateArticle(id uint, req models.CreateArticleRequest) (*models.Article, error) {
	article, err := s.articalDao.GetById(id)
	if err != nil {
		return nil, errors.New("文章不存在")
	}
	// 更新字段
	article.Title = req.Title
	article.Content = req.Content
	article.CoverImage = req.CoverImage
	article.State = req.State
	article.TOC = req.TOC
	// 更新发布时间
	// ...
	article.UpdatedAt = time.Now()
	if err := s.articalDao.Update(article); err != nil {
		return nil, err
	}
	return article, nil
}

// 删除文章
func (s *articalService) DeleteArticle(id uint) error {
	return s.articalDao.Delete(id)
}
